<i18n locale="zh-CN" lang="yaml">
Lock Script Set        : 锁定脚本集
Allow Others to Operate: 允许其他人操作

Select User...       : 选择用户...
Allowed Operations...: 允许的操作...
Add Member           : 添加成员

Read Script Code, Clone and Export Script Set              : 阅读脚本代码，克隆和导出脚本集
Read, Add and Edit Script Code, Clone and Export Script Set: 阅读、添加和编辑脚本代码，克隆和导出脚本集
Setup Script Set                                           : 配置脚本集
Add Script                                                 : 添加脚本
Setup Script                                               : 配置脚本
Delete Script                                              : 删除脚本

Please select User              : 请选择用户
Please select Allowed Operations: 请选择允许的操作
All Users                       : 所有用户

Script Set locked             : 脚本集已锁定
Script Set unlocked           : 脚本集已解锁
Script Set lock config updated: 脚本集锁定配置已更新

This Script is locked by you: 当前脚本已被您锁定
This Script is locked by other user ({user}): 当前脚本已被其他用户（{user}）锁定

Are you sure you want to unlock the Script Set and delete all the lock configs?: 您确定要解锁脚本集并删除所有锁定配置吗？
</i18n>

<!-- Generated by OpenCC START -->
<i18n locale="zh-HK" lang="yaml">
Add Member: 添加成員
Add Script: 添加腳本
All Users: 所有用户
Allow Others to Operate: 允許其他人操作
Allowed Operations...: 允許的操作...
Are you sure you want to unlock the Script Set and delete all the lock configs?: 您確定要解鎖腳本集並刪除所有鎖定配置嗎？
Delete Script: 刪除腳本
Lock Script Set: 鎖定腳本集
Please select Allowed Operations: 請選擇允許的操作
Please select User: 請選擇用户
Read Script Code, Clone and Export Script Set: 閲讀腳本代碼，克隆和導出腳本集
Read, Add and Edit Script Code, Clone and Export Script Set: 閲讀、添加和編輯腳本代碼，克隆和導出腳本集
Script Set lock config updated: 腳本集鎖定配置已更新
Script Set locked: 腳本集已鎖定
Script Set unlocked: 腳本集已解鎖
Select User...: 選擇用户...
Setup Script: 配置腳本
Setup Script Set: 配置腳本集
This Script is locked by other user ({user}): 當前腳本已被其他用户（{user}）鎖定
This Script is locked by you: 當前腳本已被您鎖定
</i18n>
<i18n locale="zh-TW" lang="yaml">
Add Member: 新增成員
Add Script: 新增指令碼
All Users: 所有使用者
Allow Others to Operate: 允許其他人操作
Allowed Operations...: 允許的操作...
Are you sure you want to unlock the Script Set and delete all the lock configs?: 您確定要解鎖指令碼集並刪除所有鎖定配置嗎？
Delete Script: 刪除指令碼
Lock Script Set: 鎖定指令碼集
Please select Allowed Operations: 請選擇允許的操作
Please select User: 請選擇使用者
Read Script Code, Clone and Export Script Set: 閱讀指令碼程式碼，克隆和匯出指令碼集
Read, Add and Edit Script Code, Clone and Export Script Set: 閱讀、新增和編輯指令碼程式碼，克隆和匯出指令碼集
Script Set lock config updated: 指令碼集鎖定配置已更新
Script Set locked: 指令碼集已鎖定
Script Set unlocked: 指令碼集已解鎖
Select User...: 選擇使用者...
Setup Script: 配置指令碼
Setup Script Set: 配置指令碼集
This Script is locked by other user ({user}): 當前指令碼已被其他使用者（{user}）鎖定
This Script is locked by you: 當前指令碼已被您鎖定
</i18n>
<!-- Generated by OpenCC END -->

<template>
  <el-dialog
    id="ScriptSetLockConfig"
    :visible.sync="show"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="750px">
    <template slot="title">
      {{ $t('Lock Script Set') }} <code class="text-main">{{ data.title || data.id }}</code>
    </template>

    <el-container direction="vertical">
      <el-main>
        <div class="setup-form">
          <el-form ref="form" label-width="65px" :model="form" :disabled="!can([ 'scriptSet_setup' ])" :rules="formRules">
            <el-form-item>
              <InfoBlock v-if="isLockedByMe" type="success" :title="$t('This Script is locked by you')" />
              <InfoBlock v-else-if="isLockedByOther" :type="can([ 'scriptSet_setup' ]) ? 'warning' : 'error'" :title="$t('This Script is locked by other user ({user})', { user: lockedByUser })" />
            </el-form-item>

            <el-form-item class="setup-divider">
              <el-divider content-position="left"><h1>{{ $t('Allow Others to Operate') }}</h1></el-divider>
            </el-form-item>

            <template v-for="(member, index) in form.lockConfigJSON.members || []">
              <el-form-item
                class="lock-config-members"
                :label="`#${index + 1}`"
                :key="`lock-config-member-user-id-${index}`"
                :prop="`lockConfigJSON.members.${index}.userId`"
                :rules="formRules_userId">
                <el-select
                  :placeholder="$t('Select User...')"
                  :no-data-text="$t('No Data')"
                  filterable
                  v-model="member.userId">
                  <el-option-group>
                    <el-option :label="$t('All Users')" key="_ALL" value="_ALL"></el-option>
                  </el-option-group>
                  <el-option-group>
                    <el-option
                      v-for="item in users"
                      :key="item.id"
                      :label="item.name || item.username"
                      :value="item.id">
                      <span class="select-item-name">
                        <template v-if="item.name">{{ item.name }} / </template><code class="code-font">{{ item.username }}</code>
                      </span>
                      <code class="select-item-id code-font">ID: {{ item.id }}</code>
                    </el-option>
                  </el-option-group>
                </el-select>

                <!-- Delete button -->
                <el-link type="danger" class="lock-config-members-button right-button" @click.prevent="removeMember(index)">{{ $t('Delete') }}</el-link>
              </el-form-item>

              <el-form-item
                class="lock-config-members"
                :key="`lock-config-member-allowed-operations-${index}`"
                :prop="`lockConfigJSON.members.${index}.allowedOperations`"
                :rules="formRules_allowedOperations">
                <el-select
                  :placeholder="$t('Allowed Operations...')"
                  :no-data-text="$t('No Data')"
                  filterable
                  multiple
                  v-model="member.allowedOperations">
                  <el-option :label="$t('Read Script Code, Clone and Export Script Set')" value="scriptSet_readScriptCode"></el-option>
                  <el-option :label="$t('Read, Add and Edit Script Code, Clone and Export Script Set')" value="scriptSet_editScriptCode"></el-option>
                  <el-option :label="$t('Setup Script Set')" value="scriptSet_setup"></el-option>
                  <el-option :label="$t('Setup Script')" value="scriptSet_setupScript"></el-option>
                  <el-option :label="$t('Delete Script')" value="scriptSet_deleteScript"></el-option>
                </el-select>
              </el-form-item>
            </template>
            <el-form-item>
              <el-link
                type="primary"
                @click="addMember">
                <i class="fa fa-fw fa-plus"></i>
                {{ $t('Add Member') }}
              </el-link>
            </el-form-item>

            <el-form-item class="setup-footer">
              <el-button v-if="isLockedByMe" type="info" plain class="float-left" @click="submitData('unlock')">{{ $t('Unlock') }}</el-button>
              <el-button type="primary" v-prevent-re-click @click="submitData('lock')">{{ isLockedByMe ? $t('Update') : $t('Lock') }}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>
  </el-dialog>
</template>

<script>
export default {
  name: 'ScriptSetLockConfig',
  components: {
  },
  watch: {
    show(val) {
      if (val && this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
  },
  methods: {
    async loadData(id) {
      this.data.id = id;

      let apiRes = await this.T.callAPI_getOne('/api/v1/script-sets/do/list', this.scriptSetId, {
        query: {
          fields: [
            'id',
            'title',
            'lockedByUserId',
            'lockConfigJSON',
            'lockedByUserUsername',
            'lockedByUserName',
            'lockConfigMemberAllowMap',
          ]
        }
      });
      if (!apiRes || !apiRes.ok) return;

      this.data = apiRes.data;

      // Ensure lockConfigJSON havs a value
      this.data.lockConfigJSON = this.data.lockConfigJSON || {};

      let nextForm = {};
      Object.keys(this.form).forEach(f => nextForm[f] = this.data[f]);
      this.form = nextForm;

      // Load user list
      apiRes = await this.T.callAPI_get('/api/v1/users/do/list', {
        query: {
          fields: [
            'id',
            'name',
            'username',
          ],
        },
      });
      if (!apiRes || !apiRes.ok) return;
      this.users = apiRes.data;

      this.show = true;
    },
    async submitData(operation) {
      try {
        await this.$refs.form.validate();
      } catch(err) {
        return console.error(err);
      }

      let dataId = null;
      switch(operation) {
        case 'lock':
          dataId = await this.lockData();
          break;

        case 'unlock':
          dataId = await this.unlockData();
          break;
      }

      if (dataId) {
        this.$store.commit('updateEditor_selectedItemId', null);
      }
    },
    async lockData() {
      let _formData = this.T.jsonCopy(this.form);
      delete _formData.id;

      _formData.isLocked = true;

      let apiRes = await this.T.callAPI('post', '/api/v1/script-sets/:id/do/modify', {
        params  : { id: this.scriptSetId },
        body    : { data: _formData },
        feedback: { okMessage: this.isLockedByMe ? this.$t('Script Set lock config updated')
                                                 : this.$t('Script Set locked') },
      });
      if (!apiRes || !apiRes.ok) return;

      this.$store.commit('updateScriptListSyncTime');
      this.show = false;

      return this.scriptSetId;
    },
    async unlockData() {
      if (!await this.T.confirm(this.$t('Are you sure you want to unlock the Script Set and delete all the lock configs?'))) return;

      let apiRes = await this.T.callAPI('post', '/api/v1/script-sets/:id/do/modify', {
        params  : { id: this.scriptSetId },
        body    : { data: { isLocked: false } },
        feedback: { okMessage: this.$t('Script Set unlocked') },
      });
      if (!apiRes || !apiRes.ok) return;

      this.$store.commit('updateScriptListSyncTime');
      this.show = false;

      return this.scriptSetId;
    },

    addMember() {
      if (this.T.isNothing(this.form.lockConfigJSON.members)) {
        this.$set(this.form.lockConfigJSON, 'members', []);
      }
      this.form.lockConfigJSON.members.push({
        userId           : '',
        allowedOperations: [],
      });
    },
    removeMember(index) {
      this.form.lockConfigJSON.members.splice(index, 1);
    },
    can(operation) {
      return this.common.lockConfigCan(this.lockedByUserId, this.data.lockConfigMemberAllowMap, operation);
    },
  },
  computed: {
    scriptSetId() {
      return this.data.id;
    },

    lockedByUserId() {
      return this.data.lockedByUserId;
    },
    lockedByUser() {
      return this.data.lockedByUserName || this.data.lockedByUsername;
    },
    isLockedByMe() {
      return this.lockedByUserId === this.$store.getters.userId;
    },
    isLockedByOther() {
      return this.lockedByUserId && !this.isLockedByMe;
    },
  },
  props: {
  },
  data() {
    return {
      show: false,

      data : {},
      users: [],

      form: {
        lockConfigJSON: [],
      },
      formRules: {
      },
      formRules_userId: {
        trigger: 'blur',
        message : this.$t('Please select User'),
        required: true,
      },
      formRules_allowedOperations: {
        trigger: 'blur',
        message : this.$t('Please select Allowed Operations'),
        required: true,
      },
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.lock-config-members .el-select {
  width: 500px !important;
}
.lock-config-members-button {
  margin-left: 10px;
}
.select-item-name {
  float: left;
}
.select-item-id {
  float: right;
  padding-left: 30px;
  font-size: 12px;
}
</style>
